import React from "react";
import { connect } from "dva";
import { Form, Input, Select, Modal, Spin } from "antd"; // Switch
import { equals } from "@cbd/utils";
import {
  formatParameters,
  // formatFormParameters,
} from "components/flowdetailpannel/FlowParameters";
import { openNotificationWithIcon } from "../../../../utils/comm";

const { Option } = Select;
const { TextArea } = Input;

const formItemLayout1 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const formItemLayout2 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 10 },
};

@Form.create()
@connect(({ loading }) => ({
  loading: loading.effects["FlowConfigure/getModelDetail"],
}))
class CreateFlow extends React.Component {
  state = {
    bussiesArr: [],
    flowParameters: [],
  };

  openNotificationWithIcon = openNotificationWithIcon.bind(this);

  componentDidMount() {
    const { appList, appBusinessObj } = this.props;

    this.setFormValue();

    if (appList.length > 0) {
      const appId = appList[0].id;
      const bussiesArr = appBusinessObj[appId] || [];
      // const busiId = bussiesArr.length > 0 ? bussiesArr[0].id : '';
      // form.setFieldsValue({ appId: '', busiId: '' });
      this.setState({ bussiesArr });
    }
  }

  componentDidUpdate(preProps) {
    const { data, route, appBusinessObj } = this.props;
    if (!equals(data, preProps.data)) {
      this.setFormValue();
      this.changeBuss();
    }
    if (!equals(route, preProps.route)) {
      if (route.length > 1) {
        const appId = route[1];
        const bussiesArr = appBusinessObj[appId] || [];
        this.setBussiesArr(bussiesArr);
      }
    }
  }

  setBussiesArr = (arr) => {
    this.setState({ bussiesArr: arr });
  };

  setFormValue = () => {
    const { data, form } = this.props;
    if (data) {
      const {
        appId,
        busiId,
        modelId,
        modelKey = "",
        modelName: name,
        description,
      } = data;
      this.modelId = modelId;
      // dispatch({
      //   type: "FlowConfigure/getModelVariables",
      //   payload: { modelId },
      // }).then(({ errCode, datas }) => {
      //   if (`${errCode}` === "0") {
      //     const flowParameters = formatFormParameters(datas);
      //     this.setState({ flowParameters });
      //   }
      // });
      form.setFieldsValue({
        appId,
        busiId,
        key: `${modelKey}copy`,
        name,
        description,
      });
    }
  };

  changeBuss = () => {
    const { data = {}, appList, appBusinessObj } = this.props;
    const { appId } = data || {};
    if (data.appId && appList.length > 0) {
      const bussiesArr = appBusinessObj[appId] || [];
      this.setState({ bussiesArr });
    }
  };

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, dispatch } = this.props;
    const { flowParameters } = this.state;
    // const actionType = this.modelId ? 'copy' : 'add';
    const actionType = this.modelId ? "copy" : "addNoCheck"; // noCheck 去掉cbd自带弹窗
    form.validateFields((err, values) => {
      if (err) {
        // this.setState({ activeKey: "1" });
        return;
      }
      const modelVariables = formatParameters(flowParameters);
      const params = {
        ...values,
        properties: {
          modelVariables,
        },
      };
      if (this.modelId) params.originModelId = this.modelId;
      dispatch({
        type: "FlowConfigure/addOrCopyFlow",
        payload: params,
        actionType,
      }).then(({ errCode, errMsg }) => {
        if (errCode === 0) {
          this.handleCancel();
          // form.resetFields();
          return;
        }
        this.openNotificationWithIcon(
          "error",
          "",
          errMsg || `${this.modelId ? "复制" : "添加"}失败`,
        );
      });
    });
  };

  handleCancel = () => {
    const { handleCreateVisible, form } = this.props;
    form.resetFields();
    handleCreateVisible(false);
  };

  handleAppIdChange = (value) => {
    const { appBusinessObj, form } = this.props;
    const bussiesArr = appBusinessObj[value] || [];
    const busiId = bussiesArr.length > 0 ? bussiesArr[0].id : "";
    form.setFieldsValue({ busiId });
    this.setState({ bussiesArr });
  };

  render() {
    const {
      form,
      visible,
      confirmLoading,
      appList,
      loading,
      route,
    } = this.props;
    const { bussiesArr } = this.state;
    const { getFieldDecorator } = form; // getFieldValue
    return (
      <Modal
        title="新建流程"
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        width="642px"
        centered
        confirmLoading={confirmLoading}
        destroyOnClose
      >
        <Spin spinning={!!loading}>
          <Form>
            <Form.Item label="流程名称" {...formItemLayout1}>
              {getFieldDecorator("name", {
                initialValue: "",
                rules: [
                  { required: true, message: "请输入流程名称" },
                  { max: 20, message: "流程名称长度不能超过20" },
                ],
              })(<Input maxLength={20} placeholder="请输入流程名称" />)}
            </Form.Item>
            <Form.Item label="流程编码" {...formItemLayout1}>
              {getFieldDecorator("key", {
                initialValue: "",
                rules: [
                  { required: true, message: "请输入流程编码" },
                  { max: 20, message: "编码长度不能超过20" },
                  {
                    pattern: /^[a-zA-Z_][a-zA-Z_0-9-]*$/,
                    message:
                      "支持字母、数字、下划线、中划线，须以字母或者下划线开头",
                  },
                ],
              })(<Input maxLength={20} placeholder="请输入流程编码" />)}
            </Form.Item>

            <Form.Item label="所属应用" {...formItemLayout2}>
              {getFieldDecorator("appId", {
                initialValue: route[1] || undefined,
                rules: [{ required: true, message: "请选择所属应用" }],
              })(
                <Select
                  placeholder="请选择所属应用"
                  onChange={this.handleAppIdChange}
                >
                  {appList.map((item) => (
                    <Option key={item.id} value={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="所属业务" {...formItemLayout2}>
              {getFieldDecorator("busiId", {
                initialValue: route[2] || undefined,
                rules: [{ required: true, message: "请选择所属业务" }],
              })(
                <Select placeholder="请选择所属业务">
                  {bussiesArr.map((item) => (
                    <Option key={`${item.id}${item.name}`} value={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Form.Item>
            {/* <Form.Item
                  label="是否公开流程"
                  {...formItemLayout1}
                >
                  {getFieldDecorator('isOpen', {
                    initialValue: false,
                    valuePropName: 'checked',
                    rules: [{ required: true }],
                  })(
                    <Switch style={{ width: 70 }} checkedChildren="公开" unCheckedChildren="不公开" />
                  )}
                  <span style={{ paddingLeft: 10, color: '#bfbfbf' }}>
                    {getFieldValue("isOpen") ? '公开流程后其他租户将也能看到此流程' : '不公开流程后其他租户将看不到此流程'}
                  </span>
                </Form.Item> */}
            <Form.Item label="流程说明" {...formItemLayout1}>
              {getFieldDecorator("description", {
                initialValue: "",
                rules: [{ max: 100, message: "流程说明长度不能超过100" }],
              })(<TextArea placeholder="请输入流程说明" rows={4} />)}
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    );
  }
}
export default CreateFlow;
